import serial  # 引入串口库


def Com_serial_get_data(Port, Baud, Timeout, Line, Filename, NumLines):
    # 初始化串口对象，但不立即打开串口
    ser = serial.Serial()
    ser.port = Port
    ser.baudrate = Baud
    ser.timeout = Timeout
    # 打开文件准备写入
    print("准备打开串口\r\n")
    with open(Filename, 'w') as file:
        # 打开串口
        ser.open()
        print("打开串口成功！\r\n")
        for i in range(NumLines):
            line = []
            while len(line) < Line:
                try:
                    data = ser.readline().decode().strip()
                    if data:
                        numbers = list(map(float, data.split()))
                        line.extend(numbers)
                except serial.SerialException as e:
                    print(f"Serial exception: {e}")
                    break
                except ValueError as e:
                    print(f"Value error: {e}")
                    continue
            file.write(' '.join(map(str, line)) + '\n')
            progress = (i + 1) / NumLines
            print(f"\rProgress: [{'=' * int(20 * progress)}{' ' * (20 - int(20 * progress))}] {int(100 * progress)}%",
                  end="")
        print("\n数据采集----------> OK! \r\n")
        ser.close()
        print("\n关闭串口成功！\r\n")


# 使用示例
Port = 'COM21'
Baud = 115200
Timeout = 1
Line = 384  # 每行需要保存的样本数
Filename = 't_normal.csv'  # 保存数据的文件名
NumLines = 50  # 需要收集的行数

Com_serial_get_data(Port, Baud, Timeout, Line, Filename, NumLines)
